package com.think.cloud.thinkshop.mall.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.think.common.core.utils.SpringUtils;
import com.think.common.redis.service.RedisService;
import org.springframework.stereotype.Component;

import java.time.LocalTime;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author zkthink
 */
@Component
public class RedisUtils {

    private static RedisService redisService = SpringUtils.getBean(RedisService.class);

    /**
     * 流水号日期格式
     */
    public static final String DATE_FORMAT = "yyyyMMdd";

    /**
     * 获取流水号
     *
     * @param key 参数键
     * @return 流水号
     */
    public static String getSerialNumber(String prefix, String key, String dateFormat, String numberFormat) {
        Long serialNumber = 1L;
        // 如果是第一次生成，则设置键的过期时间为当天结束
        if (!redisService.hasKey(key)) {
            LocalTime currentTime = LocalTime.now();
            Long timeout = (24 - currentTime.getHour()) * 60 * 60L - currentTime.getMinute() * 60L - currentTime.getSecond();
            redisService.setCacheObject(key, serialNumber, timeout, TimeUnit.SECONDS);
        } else {
            serialNumber = (Long) redisService.getCacheObject(key) + 1L;
            redisService.setCacheObject(key, serialNumber);
        }
        return prefix + DateUtil.format(new Date(), dateFormat) + String.format(numberFormat, serialNumber);
    }
}
